package com.zengdada.authority.controller;

import com.github.pagehelper.PageInfo;
import com.zengdada.authority.config.security.intercept.AuthorityUtil;
import com.zengdada.authority.exception.RoutineException;
import com.zengdada.authority.model.AppRole;
import com.zengdada.authority.model.AppUser;
import com.zengdada.authority.model.AppUserRoleRel;
import com.zengdada.authority.service.AppRoleAuthorityService;
import com.zengdada.authority.service.AppUserRoleRelAuthorityService;
import com.zengdada.authority.service.impl.AppRoleAuthorityServiceImpl;
import com.zengdada.authority.utils.JsonMessage;
import com.zengdada.authority.utils.mapper.Page;
import com.zengdada.authority.utils.mapper.Sort;
import com.zengdada.authority.utils.where.Where;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.zengdada.authority.utils.JsonMessage.fail;
import static com.zengdada.authority.utils.JsonMessage.success;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2018/12/11 17:29
 * @Description:
 */
@Controller
@RequestMapping("/authority/department")
public class DepartmentAuthorityController {

    @Autowired
    @Qualifier("appRoleAuthorityServiceImpl")
    AppRoleAuthorityService appRoleAuthorityService;

    @Autowired
    AuthorityUtil authorityUtil;

    @Autowired
    @Qualifier("appUserRoleRelAuthorityServiceImpl")
    AppUserRoleRelAuthorityService appUserRoleRelAuthorityService;


    @GetMapping("/page.html")
    public String page() {
        return "authority/department/page";
    }

    @RequestMapping(value = "/department_tree.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage departmentTree() {
        try {
            return success(appRoleAuthorityService.getRoleOrDepartmentTree(Collections.singletonList(AppRoleAuthorityServiceImpl.TYPE_DEPARTMENT)));
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }


    @RequestMapping(value = "/list.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage list(@RequestParam(value = "id", defaultValue = "") String id, String searchs, Page page, Sort sort) {
        try {
            if ("".equals(id)) {
                throw new RoutineException("请选择节点");
            }
            List<Where> params = new ArrayList<>();
            Where where = new Where(Where.Formula.AND,params);
            try {
                params.add(Where.formJsonString(StringEscapeUtils.unescapeHtml4(searchs)));
            } catch (Exception e) {
                throw new RoutineException("查询条件解析失败：" + e.getMessage());
            }
            params.add(new Where("type", AppRoleAuthorityServiceImpl.TYPE_DEPARTMENT));
            params.add(new Where("parentId", id));
            PageInfo<Map<String, Object>> appRolePageInfo = appRoleAuthorityService.selectDetailedPageInfoByParam(where, page, sort);
            return success(appRolePageInfo.getList(), appRolePageInfo.getTotal());
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @RequestMapping(value = "/del.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage del(@RequestParam(value = "id", defaultValue = "") String id) {
        try {
            if (appRoleAuthorityService.deleteById(id) == 0) throw new RoutineException("没有删除任何数据！！");
            return success();
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @RequestMapping(value = {"/add.do"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage add(AppRole appRole) {
        try {
            AppUser user = authorityUtil.getLoginUser();
            if (StringUtils.isBlank(appRole.getId())) {
                if (appRoleAuthorityService.add(appRole) == 0) throw new RoutineException("新增失败！！");
            } else {
                appRole.setModifyUser(user.getId());
                appRole.setModifyTime(new Date());
                if (appRoleAuthorityService.updateById(appRole) == 0) throw new RoutineException("没有修改任何数据！！");
            }
            return success();
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }


    @RequestMapping(value = "/change_user_rel.do", method = RequestMethod.POST)
    @ResponseBody
    public JsonMessage changeUserRel(String roleId, String userIds, String type) {
        try {
            if (roleId == null || userIds == null || type == null)
                throw new RuntimeException("参数错误！！");
            List<String> userIdList = Arrays.asList(userIds.split(","));
            userIdList.forEach(userId -> {
                AppUserRoleRel appUserRoleRel = new AppUserRoleRel() {{
                    setAppUserId(userId);
                    setAppRoleId(roleId);
                }};
                if ("binding".equals(type)) {
                    appUserRoleRel.setCreateTime(new Date());
                    appUserRoleRelAuthorityService.add(appUserRoleRel);
                } else if ("untie".equals(type)) {
                    appUserRoleRelAuthorityService.deleteById(appUserRoleRel);
                }
            });
            return success();
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
}
